package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.os.Parcelable
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.widget.EditText
import android.widget.TextView
import com.alibaba.android.arouter.facade.annotation.Route
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.INetCommCallback
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.util.Utils
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog
import com.kanshu.ksgb.fastread.doudou.common.view.VerificationCodeInput
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.*
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import com.kanshu.ksgb.fastread.doudou.module.personal.utils.UserInfoUtils
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_encashment.*
import org.greenrobot.eventbus.EventBus

@Route(path = ARouterConfig.PERSONAL_ENCASHMENT)
class EncashmentActivity : BaseActivity() {

    val ALIPAY = BindInfo.TYPE_ALIPAY.toInt()
    val WECHAT = BindInfo.TYPE_WECHAT.toInt()
    var phone: String? = null
    var alipayBinded = false
    var weChatBinded = false
    val apiService = RetrofitHelper.getInstance().createService(PersonCenterService::class.java)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_encashment)
        title = "零钱提现"
        alipayBinded = intent?.getBooleanExtra("alipay",false)?: false
        weChatBinded = intent?.getBooleanExtra("wechat",false)?: false

        var tvEncashRecord = TextView(this)
        tvEncashRecord.text = "提现记录"
        tvEncashRecord.setTextColor(Color.GRAY)
        tvEncashRecord.gravity = Gravity.CENTER_VERTICAL
        tvEncashRecord.setOnClickListener {
            ARouterUtils.toActivity(ARouterConfig.PERSONAL_ENCASHMENT_RECORD)
        }
        mTitle.rightContainer.addView(tvEncashRecord)
        btn_allipay.setOnClickListener {
            if(!alipayBinded){
                ToastUtil.showMessage("请先绑定支付宝提现账号")
                return@setOnClickListener
            }
            doEncashement(ALIPAY)
        }
        userBalance = intent.getIntExtra("count", 0)
        phone = intent.getStringExtra("phone")
        updateTotalView()
        btn_wechat.setOnClickListener {
            if(!weChatBinded){
                ToastUtil.showMessage("请先绑定微信提现账号")
                return@setOnClickListener
            }
            doEncashement(WECHAT)
        }
    }

    private fun updateTotalView() {
        total_amount.text = String.format("%1$.2f", userBalance.toFloat() / 100)
    }

    private var userBalance = 0
    private val MIN_ENCASHEMENT = 3000

    private fun doEncashement(type: Int): Boolean {
        val inputStr = input.text?.toString()
        if (TextUtils.isEmpty(inputStr)) {
            ToastUtil.showMessage("输入金额错误")
            return false
        }
        val inputDouble = inputStr?.toDoubleOrNull()
        Log.i("test", "input $inputDouble")
        if (inputDouble == null) {
            ToastUtil.showMessage("请输入提现金额")
            return false
        }
        val tmp = total_amount?.text?.toString()?.toDoubleOrNull()
        if (inputDouble != null && tmp != null && inputDouble > tmp) {
            ToastUtil.showMessage("提现金额不足")
            return false
        }
        var inputFen = ""
        if(inputDouble != null) {
            inputFen = (inputDouble * 100).toString()
            if ((inputDouble * 100).toInt() < 1) {
                ToastUtil.showMessage("输入金额必须大于1分")
                return false
            }
        } else {
            inputFen = "0"
        }
        if(TextUtils.equals("0", inputFen)){
            ToastUtil.showMessage("输入金额必须大于0")
            return false
        }
        if (inputFen.contains(".")) {
            inputFen = inputFen.substring(0, inputFen.lastIndexOf("."))
        }
        doEncashSubmit(inputFen,type)
        return true

    }

    override fun onPause() {
        super.onPause()
        Utils.hideSoftKeyboard(this);
    }

    private fun doEncashSubmit(inputFen:String, type: Int) {
        val params = mutableMapOf<String, String>()
        params.put("rmb", inputFen)
        params.put("type", type.toString())
        //params.put("code", valCode)
        apiService.chechWithdraw(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<String>> {
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t: BaseResult<String>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                                validateCode(params)
                        } else {
                            val msg = t?.result?.status?.msg ?: "提现失败"
                            ToastUtil.showMessage(msg)
                        }

                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        dismissLoading()
                        ToastUtil.showMessage("网络错误，稍后再试")
                    }

                })
/*
*/

    }

    private fun doShowResult(data: WithdrawResult) {
        UserInfoUtils.getUserBaseInfo(object : INetCommCallback<UserData>{
            override fun onResponse(userData: UserData?) {
                if (!TextUtils.isEmpty(userData?.account_info?.rmb_balance)) {
                    try {
                        userBalance = Integer.valueOf(userData?.account_info?.rmb_balance)
                        updateTotalView()
                    } catch (e:Exception) {

                    }
                }
            }
            override fun onError(code: Int, errDesc: String?) {
                userBalance -= data.rmb.toInt()
                updateTotalView()
            }
        })
        input.setText("")
        EventBus.getDefault().post(UpdateInfoEvent() )
        var map = HashMap<String,Parcelable>()
        map["data"]=data
        ARouterUtils.toActivity(ARouterConfig.PERSONAL_ENCASHMENT_RESULT, map)
    }

    var loadingDialog: LoadingDialog? = null

    private fun validateCode(withDrawParams:MutableMap<String,String>) {
        if (loadingDialog != null && loadingDialog!!.isShowing) {
            return
        }

        if (TextUtils.isEmpty(phone)) {
            ToastUtil.showMessage("绑定手机号后才能提现");
            return
        }
        loadingDialog = LoadingDialog(this, "")
        val helper = RetrofitHelper.getInstance()
        val params = mutableMapOf<String, String?>()
        params.put("phone", phone)
        val personService = helper.createService(PersonCenterService::class.java)
        personService.getValidateCode(params)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<String>> {
                    override fun onComplete() {
                        loadingDialog?.dismiss()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        loadingDialog?.show()
                    }

                    override fun onNext(t: BaseResult<String>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                            ToastUtil.showMessage("获取验证码成功")
                            showValidateCodeDialog(withDrawParams)
                        } else {
                            ToastUtil.showMessage("获取验证码失败,请稍后再试")
                        }
                    }

                    override fun onError(e: Throwable?) {
                        ToastUtil.showMessage("获取验证码失败,请稍后再试")
                        e?.printStackTrace()
                        loadingDialog?.dismiss()
                    }
                })
    }

    private fun showValidateCodeDialog(withDrawParams:MutableMap<String,String>) {
        val layout = LayoutInflater.from(this).inflate(R.layout.layout_code_validation, null, false)
        val dialog = Dialog(this)
        dialog.setContentView(layout)

        var code = ""
        val input1: EditText = layout.findViewById(R.id.input1)
        val input2: EditText = layout.findViewById(R.id.input2)
        val input3: EditText = layout.findViewById(R.id.input3)
        val input4: EditText = layout.findViewById(R.id.input4)
        val input: VerificationCodeInput = layout.findViewById(R.id.input_verification)
        input.setOnCompleteListener { content -> code = content ?: "" }
        input1.addTextChangeListener {
            if (TextUtils.isEmpty(it)) {

            } else {
                input2.requestFocus()
            }
        }
        input2.addTextChangeListener {
            if (TextUtils.isEmpty(it)) {
                input1.requestFocus()

            } else {
                input3.requestFocus()
            }
        }
        input3.addTextChangeListener {
            if (TextUtils.isEmpty(it)) {
                input2.requestFocus()
            } else {
                input4.requestFocus()
            }
        }
        input4.addTextChangeListener {
            if (TextUtils.isEmpty(it)) {
                input3.requestFocus()
            } else {
            }
        }
/*        input2.setOnKeyListener { v, keyCode, event ->
            if(KeyEvent.KEYCODE_DEL == keyCode && TextUtils.isEmpty(input4.text.toString())) {
                return@setOnKeyListener input1.requestFocus()
            }
            return@setOnKeyListener false
        }
        input3.setOnKeyListener { v, keyCode, event ->
            if(KeyEvent.KEYCODE_DEL == keyCode && TextUtils.isEmpty(input4.text.toString())) {
                return@setOnKeyListener input2.requestFocus()
            }
            return@setOnKeyListener false
        }
        input4.setOnKeyListener { v, keyCode, event ->
            if(KeyEvent.KEYCODE_DEL == keyCode && TextUtils.isEmpty(input4.text.toString())) {
                return@setOnKeyListener input3.requestFocus()
            }
            return@setOnKeyListener false
        }*/
        val btnSubmit: TextView = layout.findViewById(R.id.btn_submit)
        btnSubmit.setOnClickListener {
//            val txt1 = input1.text.toString()
//            val txt2 = input2.text.toString()
//            val txt3 = input3.text.toString()
//            val txt4 = input4.text.toString()
            //val code = txt1 + txt2 + txt3 + txt4
            if (code.length != 4) {
                ToastUtil.showMessage("验证码输入长度不正确")
                return@setOnClickListener
            }
            dialog.dismiss()
            checkCode(code,withDrawParams)
           // doEncashSubmit(inputDouble, type, code)
        }
        dialog.show()
    }

    private fun checkCode(code:String , withDrawParams: MutableMap<String, String>){
        withDrawParams.put("code",code)
        apiService.withdrawApply(withDrawParams)
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<WithdrawResult>> {
                    override fun onComplete() {
                        dismissLoading()
                    }

                    override fun onSubscribe(d: Disposable?) {
                        showLoading("")
                    }

                    override fun onNext(t: BaseResult<WithdrawResult>?) {
                        val code = t?.result?.status?.code ?: -1
                        if (code == 0) {
                            val data = t?.result?.data
                            //doShowResult(data)
                            if(data != null){
                                ToastUtil.showMessage("提现成功")
                                doShowResult(data)
                            }else{
                                ToastUtil.showMessage("服务器错误，请稍后再试")
                            }
                        } else {
                            val msg = t?.result?.status?.msg ?: "提现失败"
                            ToastUtil.showMessage(msg)
                        }

                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        dismissLoading()
                        ToastUtil.showMessage("网络错误，稍后再试")
                    }

                })

    }


    companion object {
        @JvmStatic
        fun actionStart(activity: Activity, count: Int, phone: String?, alipay:Boolean, weChat:Boolean) {
            val intent = Intent(activity, EncashmentActivity::class.java);
            if (!TextUtils.isEmpty(phone)) {
                intent.putExtra("phone", phone)
            }
            intent.putExtra("alipay", alipay)
            intent.putExtra("wechat", weChat)
            intent.putExtra("count", count)
            activity.startActivity(intent)
        }
    }
}

fun EditText.addTextChangeListener(method: (CharSequence?) -> Unit) {
    this.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            method.invoke(s)
        }

    })

}